﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.OAuthLogin.Config;
using Microsoft.AspNetCore.OAuthLogin.Model;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace Microsoft.AspNetCore.OAuthLogin
{
    /// <summary>
    /// 微博登陆
    /// </summary>
    public class Weibo : BaseLogin
    {
        private OAuthCredentials _credentials;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="options"></param>
        public Weibo(IHttpContextAccessor httpContextAccessor, IOptions<OAuthCredentials> options)
            : base(httpContextAccessor)
        {
            this._credentials = options.Value;
        }

        private string authorize_url { get; set; }

        /// <summary>
        /// 跳转的地址
        /// </summary>
        public override string Authorize_Url => authorize_url;

        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <returns></returns>
        public OAuthResult Authorize()
        {
            OAuthResult result = new OAuthResult();

            authorize_url = $"https://api.weibo.com/oauth2/authorize?client_id={_credentials.Weibo.client_id}&response_type=code&redirect_uri={CallbackUrl}";

            if (String.IsNullOrEmpty(AuthorizeCode))
            {
                return null;
            }
            result.Token = Accesstoken(AuthorizeCode);
            if (result.Token != null)
            {
                result.User = UserInfo(result.Token.Value<string>("access_token"), result.Token.Value<string>("uid"));
                if (result.User != null)
                {
                    result.code = 0;
                    result.User = result.User;
                }
                else
                {
                    result.errormsg = "获取微博用户信息失败";
                    result.code = 2;
                }
            }
            else
            {
                result.errormsg = "获取token失败";
                result.code = 1;
            }
            return result;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private JObject Accesstoken(string code)
        {
            string oauth_url = $"https://api.weibo.com/oauth2/access_token?client_id={_credentials.Weibo.client_id}&client_secret={_credentials.Weibo.client_secret}&grant_type=authorization_code&code={code}&redirect_uri={CallbackUrl}";
            var data = new SortedDictionary<string, string>();

            using (var httpClient = new HttpClient())
            {
                var response = httpClient.PostAsync(oauth_url, null).Result;
                return JsonConvert.DeserializeObject<JObject>(response.Content.ReadAsStringAsync().Result);
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        private JObject UserInfo(string token, string uid)
        {
            string user_info_url = $"https://api.weibo.com/2/users/show.json?access_token={token}&uid={uid}";
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync(user_info_url).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                var user = JsonConvert.DeserializeObject<JObject>(result);
                return user;
            }
        }


    }
}
